package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
@Slf4j
public class SupplyTaskHandler implements MsgHandler {
    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) throws IOException {
        try {
            //1.解析协议内容
            var supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
            if (supplyContract == null || supplyContract.getSupplyData() == null || supplyContract.getSupplyData().size() <= 0)
                return;
            //2.找出被指派人
            VmVO vmInfo = vmService.getVMInfo(supplyContract.getInnerCode());//根据设备id查询售货机信息
            if (vmInfo==null) return;
            int leastUserId = taskService.getLeastUser(vmInfo.getRegionId(), false);//根据设备区域id查询工单最少的运营员工并派发工单
            if (leastUserId==0) return;

            //3.创建补货工单
            var taskViewModel = new TaskViewModel();
            taskViewModel.setCreateType(0); //创建类型  自动创建
            taskViewModel.setInnerCode(supplyContract.getInnerCode()); //设备编码
            taskViewModel.setUserId(leastUserId); //工单指派人id设置为目前工单量最少人id
            taskViewModel.setAssignorId(0); //创建人id   自动创建
            taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY); //工单类型为补货工单
            taskViewModel.setDesc("自动补货工单");
            //设置补货明细表详情
            taskViewModel.setDetails(
                    supplyContract.getSupplyData().stream().map(channelNews ->{
                        var taskDetails = new TaskDetailsViewModel();
                        taskDetails.setChannelCode(channelNews.getChannelId());//货道编码
                        taskDetails.setExpectCapacity(channelNews.getCapacity());//期望补货数量
                        taskDetails.setSkuId(channelNews.getSkuId());//商品id
                        taskDetails.setSkuName(channelNews.getSkuName()); //商品名称
                        taskDetails.setSkuImage(channelNews.getSkuImage());//商品图片
                        return taskDetails;
                    }).collect(Collectors.toList()));//补货详情
            taskService.createTask(taskViewModel);
        } catch (Exception e) {
           log.error("自动创建补货工单出错，"+e.getMessage());
        }
    }
}
